<?php
require(__DIR__ . '/common.php');
header('Content-type: application/json; charset=UTF-8');

$url = $_GET['url'];
$custom = $_GET['custom'];
$expire = intval($_GET['expire']);
if ($_GET['sign'] !== md5(implode('|', [PWD, $custom, $expire, $url]))) {
  echo json([
    'error' => '密码错误'
  ]);
  exit;
}

$forever = date('Y-m-d H:i:s', '5000000000');
$hash = md5($url);
// 如果定义了custom，就先看看有没有重复的
if (getByKey($custom) !== null) {
  echo json([
    'error' => $custom . '已存在'
  ]);
  exit;
}
// 如果不是永久有效期，那就不查询重复的
if ($expire !== 0) {
  // 查询是否有相同的URL
  $st = db()->query("SELECT * FROM `su_url` WHERE hash = '$hash' AND `expire` < '$forever' LIMIT 0, 1");
  if ($st->rowCount() > 0) {
    $row = $st->fetch(PDO::FETCH_ASSOC);
    echo json([
      'key' => $row['k']
    ]);
    exit;
  }
}
// 开始处理数据
$key = genKey($url);
$st = db()->prepare('INSERT INTO `su_url`(`k`, `hash`, `url`, `expire`) VALUES (?, ?, ?, ?)');
$st->bindValue(1, $key);
$st->bindValue(2, $hash);
$st->bindValue(3, $url);
$st->bindValue(4, $expire === 0 ? $forever : date('Y-m-d H:i:s', time() + $expire * 3600 * 24));
$st->execute();

echo json([
  'key' => $key
]);